package com.shou.lifecollege.framework.Security.service;

import cn.hutool.core.util.StrUtil;
import com.shou.lifecollege.modules.common.entity.SysPermission;
import com.shou.lifecollege.modules.common.entity.SysRole;
import com.shou.lifecollege.modules.common.entity.SysUser;
import com.shou.lifecollege.modules.common.service.SysPermissionService;
import com.shou.lifecollege.modules.common.service.SysRoleService;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: luotian
 * @Date: 2022/11/24 14:36
 */
@Component
public class SystemPermissionService {
    private final SysRoleService roleService;
    private final SysPermissionService sysPermissionService;

    /**
     * 构造器注入
     *
     * @param roleService     角色服务
     * @param sysPermissionService 资源服务
     */
    public SystemPermissionService(SysRoleService roleService, SysPermissionService sysPermissionService) {
        this.roleService = roleService;
        this.sysPermissionService = sysPermissionService;
    }

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user)
    {
        return roleService.getRoleStringByUserId(user.getUsrid());
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user)
    {
        List<SysPermission> resources = sysPermissionService.getPermissionListById(user.getUsrid());
        List<String> perms = resources.stream().map(SysPermission::getPath).collect(Collectors.toList());
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StrUtil.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 获取角色通过用户id
     *
     * @param user 用户
     * @return {@link List}<{@link SysRole}>
     */
    public List<SysRole> getRolesByUserId(SysUser user)
    {
        return roleService.getRoleByUserId(user.getUsrid());
    }

}
